import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, Empty, Form, Icon, Input, Radio, Select, message } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import useDictionary from '@/hooks/useDictionary';
import FormContainer from './FormContainer';

/**
 * 员工档案 - 家庭成员
 */
const FamilyMemberSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 列表管理
    const {
        list: familyList,
        remove: familyListRemove,
        push: familyListPush,
        getKey: familyListGetKey,
        resetList: familyListReset
    } = useDynamicList([]);
    // 字典数据
    const [emergencyRelationshipList, getEmergencyRelationshipText] = useDictionary('emergencyRelationship');
    const [liveTogetherList, getLiveTogetherText] = useDictionary('liveTogether');

    useEffect(() => {
        // 表单保存后, 重置列表的值
        familyListReset(formData.familyList);
    }, [familyListReset, formData.familyList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('familyList', { initialValue: formData.familyList || [] });
    }, [formData.familyList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            newList: familyList.map((item, index) => {
                const key = familyListGetKey(index);
                return {
                    name: values.name[key],
                    relation: values.relation[key],
                    address: values.address[key],
                    work: values.work[key],
                    contact: values.contact[key],
                    areaCode: values.areaCode[key],
                    liveTogether: values.liveTogether[key]
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        familyListReset(formData.familyList);
    };

    // 取消编辑
    const handleEdit = () => {
        if (familyList.length === 0) {
            familyListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="家庭成员"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className="dynamicList">
                    {familyList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className="dynamicListContainer">
                        {familyList.map((item, index) => (
                            <div key={familyListGetKey(index)} className="dynamicListItem">
                                {editStatus && props.isEntryGuide && (
                                    <div className="dynamicListItemHeader">家庭成员 {index + 1}</div>
                                )}
                                {editStatus && (
                                    <Icon
                                        onClick={() => familyListRemove(index)}
                                        className="dynamicListClose"
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Form.Item label="姓名">
                                    {editStatus ? (
                                        getFieldDecorator(`name[${familyListGetKey(index)}]`, {
                                            initialValue: item?.name ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入姓名'
                                                },
                                                {
                                                    min: 2,
                                                    max: 50,
                                                    message: '请输入2~50个字符'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(<Input placeholder="请输入姓名" />)
                                    ) : (
                                        <div className="multiLineText">{item?.name}</div>
                                    )}
                                </Form.Item>
                                <Form.Item label="居住住址">
                                    {editStatus ? (
                                        getFieldDecorator(`address[${familyListGetKey(index)}]`, {
                                            initialValue: item?.address ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入居住住址'
                                                },
                                                {
                                                    min: 1,
                                                    max: 50,
                                                    message: '请输入1~50个字符'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(<Input placeholder="请输入居住住址" />)
                                    ) : (
                                        <div className="multiLineText">{item?.address}</div>
                                    )}
                                </Form.Item>

                                <Form.Item label="与本人关系">
                                    {editStatus ? (
                                        getFieldDecorator(`relation[${familyListGetKey(index)}]`, {
                                            initialValue: item?.relation ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择与本人关系'
                                                }
                                            ]
                                        })(
                                            <Select
                                                placeholder="请选择与本人关系"
                                                getPopupContainer={trigger => trigger.parentElement}
                                            >
                                                {emergencyRelationshipList?.map(option => (
                                                    <Select.Option value={option.value} key={option.value}>
                                                        {option.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <span>{getEmergencyRelationshipText(item?.relation)}</span>
                                    )}
                                </Form.Item>
                                <Form.Item label="手机号码">
                                    {editStatus ? (
                                        getFieldDecorator(`contact[${familyListGetKey(index)}]`, {
                                            initialValue: item?.contact ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    validator(rule, value, callback) {
                                                        const regex = /^\d{7,11}$/;
                                                        if (!value) {
                                                            callback('手机号码不能为空');
                                                        } else if (!regex.test(value)) {
                                                            callback('只能输入7-11位数字');
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })(
                                            <Input
                                                placeholder="请填入手机号码"
                                                addonBefore={getFieldDecorator(`areaCode[${familyListGetKey(index)}]`, {
                                                    initialValue: item?.areaCode || '86'
                                                })(
                                                    <Select placeholder="区号" style={{ width: 80 }}>
                                                        <Select.Option value="86">+86</Select.Option>
                                                        <Select.Option value="65">+65</Select.Option>
                                                    </Select>
                                                )}
                                            />
                                        )
                                    ) : (
                                        <span>
                                            {item.contact
                                                ? `${item?.areaCode ? `+${item.areaCode}` : ''} ${item.contact}`
                                                : '--'}
                                        </span>
                                    )}
                                </Form.Item>

                                <Form.Item label="工作/学习单位">
                                    {editStatus ? (
                                        getFieldDecorator(`work[${familyListGetKey(index)}]`, {
                                            initialValue: item?.work ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入工作/学习单位'
                                                },
                                                {
                                                    min: 1,
                                                    max: 50,
                                                    message: '请输入1~50个字符'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(<Input placeholder="请输入工作/学习单位" />)
                                    ) : (
                                        <div className="multiLineText">{item?.work}</div>
                                    )}
                                </Form.Item>
                                <Form.Item label="是否同住">
                                    {editStatus ? (
                                        getFieldDecorator(`liveTogether[${familyListGetKey(index)}]`, {
                                            initialValue: item?.liveTogether ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择是否同住'
                                                }
                                            ]
                                        })(
                                            <Radio.Group>
                                                {liveTogetherList?.map(option => (
                                                    <Radio value={option.value} key={option.value}>
                                                        {option.text}
                                                    </Radio>
                                                ))}
                                            </Radio.Group>
                                        )
                                    ) : (
                                        <span>{getLiveTogetherText(item?.liveTogether)}</span>
                                        // <span>{item?.liveTogether === 'no' ? '否' : '是'}</span>
                                    )}
                                </Form.Item>
                            </div>
                        ))}
                    </div>
                    {editStatus ? (
                        <Button className="dynamicListAddButton" block onClick={() => familyListPush({})}>
                            +添加家庭成员
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
FamilyMemberSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

FamilyMemberSection.defaultProps = {
    saveAction: false,
    readonly: false
};

export default FamilyMemberSection;
